﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Esb.Domain.DTO;
using Esb.Domain.DomainObjects;
using Esb.Domain.Services;

namespace Esb.ManageUI.Controllers
{
    public class ManageServiceController : BaseController
    {
        //
        // GET: /ManageServices/

        /// <summary>
        /// 管理服务
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            //管理服务
            ServiceService serviceSvc = new ServiceService();
            QueryCondition condition = new QueryCondition();
            if (!string.IsNullOrEmpty(Request["ApplicationId"]))
            {
                condition.ApplicationId = int.Parse(Request["ApplicationId"]);
            }
            condition.ServiceDescription = Request["ServiceDescription"];
            condition.ServiceName = Request["ServiceRoute"];
            List<ServiceDo> result = serviceSvc.QueryServices(condition);
            return View(result);
        }

        /// <summary>
        /// 新增服务
        /// </summary>
        /// <returns></returns>
        public ActionResult AddService(ServiceDo service)
        {
            if (Request.HttpMethod != "POST")
            {
                service.AlertThreshold = 5;
                ViewBag.Add = true;
                //配置为新增服务
                return View("~/Views/Service/Index.cshtml", service);
            }
            else
            {
                ViewBag.Add = false;
                //注册服务
                ServiceService serviceSvc = new ServiceService();
                string msg = "";

                string consumers = Request["Consumers"];
                string[] consumers2 = consumers.Split(',');
                service.Consumers = new List<string>();
                foreach (string consumer in consumers2)
                {
                    //consumerId为string类型
                    //int conumserId;
                    //if (int.TryParse(consumer, out conumserId))
                    //{
                    service.Consumers.Add(consumer);
                    //}
                }

                string userName = Session["UserName"].ToString();
                bool success = serviceSvc.RegisterService(service, userName, out msg);

                if (success)
                {
                    ViewBag.Scripts = "<Script>alert('注册服务成功！');</Script>";
                }
                else
                {
                    ViewBag.Scripts = "<Script>alert('注册服务失败！可能原因：" + msg + "');</Script>";
                }

                return View("~/Views/Service/Index.cshtml", service);
            }
        }
    }
}
